<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑房源' : '新建房源'"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <!-- 核心必填字段 -->
      <el-form-item
        label="小区名称"
        prop="community_name"
      >
        <el-input
          v-model="formData.community_name"
          placeholder="请输入小区名称"
        />
      </el-form-item>

      <el-form-item
        label="房号"
        prop="room_number"
      >
        <el-input
          v-model="formData.room_number"
          placeholder="格式: 栋号-房号，如 3-101 或 A-1501"
        >
          <template #prepend>
            <el-icon><House /></el-icon>
          </template>
        </el-input>
        <el-text
          size="small"
          type="info"
          style="margin-top: 4px"
        >
          建议格式：栋号-房号（如 3-101 表示3栋101室）
        </el-text>
      </el-form-item>

      <el-form-item
        label="户型"
        prop="layout"
      >
        <div class="layout-tags">
          <el-radio-group v-model="formData.layout">
            <el-radio-button label="1室">
              1室
            </el-radio-button>
            <el-radio-button label="2室">
              2室
            </el-radio-button>
            <el-radio-button label="3室">
              3室
            </el-radio-button>
            <el-radio-button label="4+室">
              4+室
            </el-radio-button>
          </el-radio-group>
        </div>
      </el-form-item>

      <el-form-item
        label="租金(元/月)"
        prop="rent_price"
      >
        <el-input-number
          v-model="formData.rent_price"
          :min="0"
          :step="100"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item
        label="房源状态"
        prop="status"
      >
        <el-select
          v-model="formData.status"
          placeholder="请选择状态"
          style="width: 100%"
        >
          <el-option
            label="空置"
            value="vacant"
          />
          <el-option
            label="已租"
            value="rented"
          />
          <el-option
            label="装修中"
            value="renovating"
          />
          <el-option
            label="已下架"
            value="delisted"
          />
        </el-select>
      </el-form-item>

      <!-- 可选字段 -->
      <el-divider content-position="left">
        <el-text
          type="info"
          size="small"
        >
          以下为可选信息
        </el-text>
      </el-divider>

      <el-form-item
        label="详细地址"
        prop="address"
      >
        <el-input
          v-model="formData.address"
          placeholder="可选，如: XX区XX路XX号"
        />
      </el-form-item>

      <el-form-item
        label="房东电话"
        prop="landlord_phone"
      >
        <el-input
          v-model="formData.landlord_phone"
          placeholder="可选，如不知道可留空"
        />
      </el-form-item>

      <el-form-item
        label="面积(㎡)"
        prop="area"
      >
        <el-input-number
          v-model="formData.area"
          :min="0"
          :step="1"
          controls-position="right"
          style="width: 100%"
          placeholder="可选"
        />
      </el-form-item>

      <el-form-item
        label="楼层"
        prop="floor"
      >
        <el-input
          v-model="formData.floor"
          placeholder="可选，如: 中层 / 15层"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">
        取消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="handleSubmit"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
defineOptions({ name: 'PropertyDialog' })
/**
 * 房源对话框组件
 *
 * Vue3 Composition API 实现方式对比：
 *
 * 方式1: 使用 ref（当前实现）
 * - 优点: 简单直观，适合简单数据
 * - 缺点: 访问时需要 .value
 *
 * 方式2: 使用 reactive
 * - 优点: 不需要 .value，更接近原生对象
 * - 缺点: 解构会丢失响应式
 *
 * 推荐: 简单值用 ref，复杂对象用 reactive
 */
import { ref, reactive, computed, watch } from 'vue'
import { usePropertyStore } from '@/stores/property'
import type { FormInstance, FormRules } from 'element-plus'
import type { Property, PropertyCreate, PropertyUpdate } from '@/api/types'
import { House } from '@element-plus/icons-vue'

// ========== Props & Emits ==========
interface Props {
  modelValue: boolean
  propertyData?: Property | null
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

// ========== Store ==========
const propertyStore = usePropertyStore()

// ========== 响应式数据 ==========
const visible = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

const isEdit = computed(() => !!props.propertyData)

const formRef = ref<FormInstance>()
const loading = ref(false)

// 使用 reactive 管理表单数据（方式2演示）
const formData = reactive<PropertyCreate & { id?: number }>({
  community_name: '',
  address: '',
  room_number: '',
  layout: '', // 默认空，用户必须选择
  rent_price: 0,
  landlord_phone: '',
  area: undefined,
  floor: '',
  status: 'vacant',
})

// 表单验证规则
const rules: FormRules = {
  community_name: [{ required: true, message: '请输入小区名称', trigger: 'blur' }],
  room_number: [{ required: true, message: '请输入房号', trigger: 'blur' }],
  layout: [{ required: true, message: '请选择户型', trigger: 'change' }],
  rent_price: [
    { required: true, message: '请输入租金', trigger: 'blur' },
    { type: 'number', min: 1, message: '租金必须大于0', trigger: 'blur' },
  ],
  // 可选字段验证
  landlord_phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
}

// ========== 方法 ==========

/**
 * 初始化表单数据
 */
const initFormData = () => {
  if (props.propertyData) {
    Object.assign(formData, props.propertyData)
  } else {
    Object.assign(formData, {
      community_name: '',
      address: '',
      room_number: '',
      layout: '', // 默认空，强制用户选择
      rent_price: 0,
      landlord_phone: '',
      area: undefined,
      floor: '',
      status: 'vacant',
    })
  }
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    loading.value = true
    try {
      let success = false
      if (isEdit.value && formData.id) {
        // 编辑
        const { id, ...updateData } = formData
        const result = await propertyStore.updateProperty(id, updateData as PropertyUpdate)
        success = !!result
      } else {
        // 新建：按接口显式构造
        const createData: PropertyCreate = {
          community_name: formData.community_name,
          address: formData.address,
          room_number: formData.room_number,
          layout: formData.layout,
          rent_price: formData.rent_price,
          landlord_phone: formData.landlord_phone,
          area: formData.area,
          floor: formData.floor,
          status: formData.status,
        }
        const result = await propertyStore.createProperty(createData)
        success = !!result
      }

      if (success) {
        emit('success')
      }
    } finally {
      loading.value = false
    }
  })
}

/**
 * 关闭对话框
 */
const handleClose = () => {
  formRef.value?.resetFields()
  visible.value = false
}

// ========== 监听 ==========
watch(
  () => props.propertyData,
  () => {
    initFormData()
  },
  { immediate: true }
)
</script>

<style scoped>
.layout-tags {
  width: 100%;
}

.layout-tags :deep(.el-radio-group) {
  width: 100%;
  display: flex;
  gap: 8px;
}

.layout-tags :deep(.el-radio-button) {
  flex: 1;
}

.layout-tags :deep(.el-radio-button__inner) {
  width: 100%;
}
</style>
